package com.baox.agridata.synchronous.schedule;


import com.baox.agridata.synchronous.constant.TaskNameConstant;
import com.baox.agridata.synchronous.entity.quanguo.Jyzdds;
import com.baox.agridata.synchronous.entity.shanxi.SxAgricultureTask;
import com.baox.agridata.synchronous.service.quanguo.JzyDdService;
import com.baox.agridata.synchronous.service.shanxi.*;
import com.baox.agridata.synchronous.util.DateUtil;
import com.baox.agridata.synchronous.util.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.File;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 动物卫生监督管理平台----农业部的推送
 * 证的入场或者出场的定时任务在这个类中l
 */


@Slf4j
@Component
@Configuration
public class LocalPushDataToAgriculturalForOutOrIn {


    @Autowired
    private SxAgricultureTaskService sxAgricultureTaskService;


    @Autowired
    private JzyDdService jzyDdService;


    @Autowired
    private TCCAAService tccaaService;


    @Autowired
    private TCCABService tccabService;


    @Autowired
    private TCCPAService tccpaService;


    @Autowired
    private TCCPBService tccpbService;

    @Autowired
    private TCCOutAAService tccOutAAService;

    @Autowired
    private TCheckPointCheckResultService tCheckPointCheckResultService;


    @Autowired
    private SplitDataSummary splitDataSummary;

    @Value("${DbConfig.QGJYStartTime}")
    private String QGJYStartTime;


    private final String JYZ_A = "1";
    private final String JYZ_P = "2";


    /**
     * 全国检疫证到达本省信息发送表（jyz_dds）
     */
    @Async("newAsyncExecutor")
    @Scheduled(cron = "0 0/5 * * * ?")  //五分钟执行一次
    public void AllCertificateArriveLocalSendTask() {
        SxAgricultureTask sxAgricultureTask = sxAgricultureTaskService.selectTaskStatus(TaskNameConstant.AllCertificateArriveLocalSendTask);
        if (sxAgricultureTask.getZt().intValue() == 1) {
            try {
                log.info("【全国检疫证到达本省发送】定时数据同步");
                FileUtil l_file = new FileUtil();
                String l_filePath = l_file.getPath() + File.separator + "TaskConfig" + File.separator + "QGJY";
                String l_fileName = "StartTimeConfig.txt";
                ///读取最后一次同步数据的时间
                if (l_file.CheckFileExists(l_filePath, l_fileName)) {
                    QGJYStartTime = l_file.readLastLineV2(l_filePath, l_fileName);
                }
                // 获取当前时间
                LocalDateTime now = LocalDateTime.now();

                // 获取当前日期
                int currentDay = now.getDayOfMonth();
                int lastDayOfMonth = now.toLocalDate().lengthOfMonth(); // 获取当前月份的最后一天
                if (currentDay == lastDayOfMonth && now.getHour() == 23 && now.getMinute() == 40) {
                    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                    // 获取当月的第一天0点0分0秒
                    LocalDateTime firstDayOfMonth = now.withDayOfMonth(1).withHour(0).withMinute(0).withSecond(0).withNano(0);
                    QGJYStartTime = firstDayOfMonth.format(formatter);  // 格式化为 "yyyy-MM-dd 00:00:00"
                }

                List<Jyzdds> jyzddsTCCAA = tccaaService.selectJyzDDsFromTCCAA(QGJYStartTime);  //动物A证作废的数据
                List<Jyzdds> jyzddsTCCAB = tccabService.selectJyzDDsFromTCCAB(QGJYStartTime);  //动物B证作废、已回收的数据
                List<Jyzdds> jyzddsTCCPA = tccpaService.selectJyzDDsFromTCCPA(QGJYStartTime);  //产品A作废的数据
                List<Jyzdds> jyzddsTCCPB = tccpbService.selectJyzDDsFromTCCPB(QGJYStartTime);  //产品B作废的数据
                List<Jyzdds> jyzddsTCCOutAA = tccOutAAService.selectJyzDDsFromTCCOutAA(QGJYStartTime); //过站数据
                List<Jyzdds> jyzddsTCheckResult = tCheckPointCheckResultService.selectJyzDDsFromCheckResult(QGJYStartTime);

                List<Jyzdds> jsyDDsList = Stream.of(jyzddsTCCAA, jyzddsTCCAB, jyzddsTCCPA, jyzddsTCCPB, jyzddsTCCOutAA, jyzddsTCheckResult).flatMap(Collection::stream).collect(Collectors.toList());
                // 写入当前时间
                String endTime = DateUtil.dateToMinute(new Date()) + ":00";
                if (jsyDDsList != null && jsyDDsList.stream().count() > 0) {
                    Integer result = splitDataSummary.interceptListArriveCertificate(jsyDDsList);
                    if (result != null && result.intValue() > 0) {
                        l_file.WriteContent(endTime, l_filePath, l_fileName);
                        log.info("【全国检疫证到达本省发送】，本期时间节点为:{}--{},同步数据总条目为：{},数据库插入结果为：{}", QGJYStartTime, endTime, jsyDDsList.size(), result.intValue());
                        log.info("【全国检疫证到达本省发送】，本期时间节点为:{}--{},total：{},AnimalA：{},AnimalB：{},ProductA：{},ProductB：{},OutAnimalA：{},CheckResult: {}",
                                QGJYStartTime, endTime, jsyDDsList.size(), jyzddsTCCAA.size(), jyzddsTCCAB.size(), jyzddsTCCPA.size(), jyzddsTCCPB.size(), jyzddsTCCOutAA.size(), jyzddsTCheckResult.size());
                    }
                } else {
                    //如果为当前月份的最后一天的23:40分则不会更新文件
                    l_file.WriteContent(endTime, l_filePath, l_fileName);
                    log.info("【全国检疫证到达本省发送】,本期时间节点为:{}---{},同步数据总条目为：{},", QGJYStartTime, endTime, jsyDDsList.size());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            log.info("全国检疫证到达本省发送【jyz_dds】同步任务未开启");
        }
    }


    /**
     * 全国检疫证到达信息接收表36（jyz_dd）
     */
    @Async("newAsyncExecutor")
    @Scheduled(cron = "0 0/5 * * * ?")
    public void AllCertificateArriveLocalReceiveTask() {
        SxAgricultureTask sxAgricultureTask = sxAgricultureTaskService.selectTaskStatus(TaskNameConstant.AllCertificateArriveLocalReceiveTask);
        if (sxAgricultureTask.getZt().intValue() == 1) {
            log.info("全国检疫证到达本省【jyz_dd】同步任务开启");
            try {
                List<Jyzdds> l_list = jzyDdService.getJyzDdArriveReceive(); //全国检疫证到达信息接收
                Integer result = 0;
                if (null != l_list && l_list.size() > 0) {
                    for (Jyzdds jyzdds : l_list) {
                        if (JYZ_A.equals(jyzdds.getJyzlx())) {  // 动物检疫证
                            result += splitDataSummary.operationTCCOutAAData(jyzdds);
                        } else if (JYZ_P.equals(jyzdds.getJyzlx())) {   //产品检疫证
                            result += splitDataSummary.operationTCCOutPAData(jyzdds);
                        }
                    }
                }
                log.info("全国检疫证到达本省接收数据同步，总计查出数据{}条,操作数据{}条", l_list.size(), result.intValue());
            } catch (Exception e) {
                log.error("全国检疫证到达本省接收数据同步失败:" + e.getMessage());
            }
        } else {
            log.info("全国检疫证到达本省【jyz_dd】同步任务未开启");
        }
    }
}
